package top.hcode.hoj.utils;

import com.alibaba.druid.util.StringUtils;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密解密
 */
public class AesUtils {

    static String key = "abcdefg123456789";
    static String iv = "123456789abcdefg";
    /**
     * AES解密
     */

    public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception {
        try{
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            byte[] temp = iv.getBytes("UTF-8");
            IvParameterSpec iv = new IvParameterSpec(temp);

            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"), iv);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);

            System.out.print(new String(decryptBytes));
            return new String(decryptBytes);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //AES 解密
    public static String decryptAES(String encryptStr) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr));
    }
    public static byte[] base64Decode(String base64Code) throws Exception{
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
    }

}